package business

import (
	"end/config"
	"end/entry"
	"end/httpEntry"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"net/http"
	"time"
)

// IsBusiness 商家检测函数
func IsBusiness(r *gin.Engine) {
	r.GET("/business/detection", httpEntry.LoginMiddleware(), httpEntry.BusinessMiddleware(), func(context *gin.Context) {
		context.JSON(http.StatusOK, httpEntry.BaseResponse{
			Code:    200,
			Message: "我是商家",
		})
	})
}

type AddRequest struct {
	FirstImg        string `json:"first_img" binding:"required"`
	BusinessLicense string `json:"business_license" binding:"required"`
	Name            string `json:"name"  binding:"required"`
	Message         string `json:"message" binding:"required"`
	Address         string `json:"address" binding:"required"`
	Phone           string `json:"phone" binding:"required"`
	Starttime       string `json:"starttime" binding:"required"`
	Endtime         string `json:"endtime" binding:"required"`
}

type UpdateRequest struct {
	FirstImg  string `json:"first_img"`
	Name      string `json:"name"`
	Message   string `json:"message"`
	Address   string `json:"address"`
	Phone     string `json:"phone"`
	Starttime string `json:"starttime"`
	Endtime   string `json:"endtime"`
}

type AllRequest struct {
	Page int `json:"page" binding:"required"`
}

type DelRequest struct {
	Id int `json:"id" binding:"required"`
}

// AddBusiness 添加商家
func AddBusiness(r *gin.Engine) {
	r.POST("/business/add", httpEntry.LoginMiddleware(), func(context *gin.Context) {
		var addRequest AddRequest
		err := context.ShouldBind(&addRequest)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		// 判断是否是店员
		userinfo := context.MustGet("userinfo").(config.UserInfo)
		db := config.GetDb()
		var clerk entry.Clerk
		result := db.Where("userid = ?", userinfo.Id).First(&clerk)
		if result.Error == nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10033,
				Error: "已经是店员无法注册商家",
			})
			return
		}
		business := entry.Business{}
		err = copier.Copy(&business, &addRequest)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10014,
				Error: httpEntry.ERROR10014,
			})
			return
		}
		business.UserID = userinfo.Id
		business.Status = httpEntry.STATUS1
		business.CreateTime = time.Now()
		result = db.Create(&business)
		// 检查错误
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10017,
				Error: httpEntry.ERROR10017,
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "注册成功",
			"data":    business,
		})
	})
}

// AllBusiness 全部商家
func AllBusiness(r *gin.Engine) {
	r.POST("/business/all", httpEntry.LoginMiddleware(), func(context *gin.Context) {
		var allRequest AllRequest
		err := context.ShouldBind(&allRequest)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		db := config.GetDb()
		var status int
		status |= httpEntry.STATUS2
		var business []entry.Business
		db.Where("status & ?", status).
			Offset((allRequest.Page - 1) * 20).
			Limit(20).
			Order("createtime desc").
			Find(&business)
		context.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "成功",
			"data":    business,
		})
	})
}

// DelBusiness 删除商家
func DelBusiness(r *gin.Engine) {
	r.POST("/business/del", httpEntry.LoginMiddleware(), httpEntry.Admin1Middleware(), func(context *gin.Context) {
		db := config.GetDb()
		var delRequest DelRequest
		err := context.ShouldBind(&delRequest)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		// 删除商家
		config.Lock()
		defer config.Unlock()
		result := db.Delete(&entry.Business{}, delRequest.Id)
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10005,
				Error: httpEntry.ERROR10009,
			})
			return
		}
		// 删除所有
		db.Where("businessid = ?", delRequest.Id).Delete(&entry.Commodity{})
		context.JSON(http.StatusOK, httpEntry.BaseResponse{
			Code:    200,
			Message: "删除成功",
		})
	})
}

// UpdateBusiness 修改商家信息
func UpdateBusiness(r *gin.Engine) {
	r.POST("/business/update", httpEntry.LoginMiddleware(), httpEntry.BusinessMiddleware(), func(context *gin.Context) {
		var request UpdateRequest
		err := context.BindJSON(&request)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		toMap, err := config.UpdateToMap(&request)
		if err != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10014,
				Error: httpEntry.ERROR10014,
			})
			return
		}
		userinfo := context.MustGet("userinfo").(config.UserInfo)
		db := config.GetDb()
		result := db.Model(&entry.Business{}).Where("id = ?", userinfo.Id).Updates(toMap)
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10014,
				Error: httpEntry.ERROR10014,
			})
			return
		}
		context.JSON(http.StatusOK, httpEntry.BaseResponse{
			Code:    200,
			Message: "修改成功",
		})
	})
}

// InfoBusiness 详情
func InfoBusiness(r *gin.Engine) {
	r.GET("/business/info/:id", httpEntry.LoginMiddleware(), func(context *gin.Context) {
		id := context.Param("id")
		db := config.GetDb()
		var business entry.Business
		result := db.Where("id = ?", id).First(&business)
		if result.Error != nil {
			context.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10014,
				Error: httpEntry.ERROR10014,
			})
			return
		}
		context.JSON(http.StatusOK, gin.H{
			"code":    200,
			"message": "查询成功",
			"data":    business,
		})
	})
}

type AuditBusinessRequest struct {
	Result int `json:"result" binding:"required"`
	Bid    int `json:"bid" binding:"required"`
}

func AuditBusiness(r *gin.Engine) {
	r.POST("/business/audit", httpEntry.LoginMiddleware(), httpEntry.Admin1Middleware(), func(c *gin.Context) {
		var auditBusinessRequest AuditBusinessRequest
		err := c.ShouldBind(&auditBusinessRequest)
		if err != nil {
			c.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		var status int
		switch auditBusinessRequest.Result {
		case 1:
			status = httpEntry.STATUS2
		case 2:
			status = httpEntry.STATUS3
		default:
			c.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10006,
				Error: httpEntry.ERROR10006,
			})
			return
		}
		err = config.GetDb().Model(&entry.Business{}).
			Where("id = ?", auditBusinessRequest.Bid).Updates(map[string]interface{}{"status": status}).Error
		if err != nil {
			c.JSON(http.StatusOK, httpEntry.BaseResponse{
				Code:  10005,
				Error: httpEntry.ERROR10005,
			})
			return
		}
		c.JSON(http.StatusOK, httpEntry.BaseResponse{
			Code:    200,
			Message: "操作成功",
		})
	})
}
